#include "serial.h"

rt_device_t device_ext_uart;
uint8_t serial_buff[SERIAL_BUFFSZ], serial_data[SERIAL_BUFFSZ]="";
rt_tick_t recieve_time;

rt_err_t ext_uart_init(){
    device_ext_uart = rt_device_find(EXT_UART_DEV);

    struct serial_configure ext_uart_conf;
    ext_uart_conf.baud_rate = BAUD_RATE_115200;
    ext_uart_conf.data_bits = DATA_BITS_8;
    ext_uart_conf.parity = PARITY_NONE;
    ext_uart_conf.stop_bits = STOP_BITS_1;
    ext_uart_conf.bufsz = SERIAL_BUFFSZ;

    rt_device_control(device_ext_uart, RT_DEVICE_CTRL_CONFIG, &ext_uart_conf);
    rt_device_open(device_ext_uart, RT_DEVICE_FLAG_INT_RX);
    rt_device_set_rx_indicate(device_ext_uart, ext_uart_event);
    return RT_EOK;
}

rt_err_t ext_uart_event(rt_device_t dev, rt_size_t size){
    static uint8_t *b = serial_buff;
    rt_device_read(dev, 0, b, 1);
    /*结束位为0x7f*/
    if (*b != 0x7f){
        ++b;
        /*防止缓冲区溢出*/
        if (b-serial_buff > SERIAL_BUFFSZ){
            b = serial_buff;
            return RT_ERROR;
        }
        return RT_EOK;
    }else{
        b = serial_buff;
        /*复制数据*/
        for (int i=0; i<SERIAL_BUFFSZ; ++i){
            serial_data[i] = serial_buff[i];
        }
        recieve_time = rt_tick_get_millisecond();
        /*校验起始位*/
        if (serial_buff[0]==0x81){
            return RT_EOK;
        }else{
            return RT_ERROR;
        }
    }
    return RT_EOK;
}

